import { Inject, Injectable } from '@nestjs/common';
import { PrismaService } from 'src/modules/prisma/prisma.service';

@Injectable()
export class ChatroomService {
  @Inject(PrismaService)
  private prismaService: PrismaService;

  async createOneToOneChatroom(userId: number, friendId: number) {
    const { id, name } = await this.prismaService.chatroom.create({
      data: {
        name: `聊天室${userId}-${friendId}`,
        type: false,
      },
      select: {
        id: true,
        name: true,
      },
    });

    await this.prismaService.userChatroom.create({
      data: {
        userId,
        chatroomId: id,
      },
    });

    await this.prismaService.userChatroom.create({
      data: {
        userId: friendId,
        chatroomId: id,
      },
    });

    return {
      name,
      message: '聊天室创建成功',
    };
  }

  async createGroupChatroom(name: string, userId: number) {
    const { id, name: chatName } = await this.prismaService.chatroom.create({
      data: {
        name,
        type: true,
      },
      select: {
        id: true,
        name: true,
      },
    });

    await this.prismaService.userChatroom.create({
      data: {
        userId,
        chatroomId: id,
      },
    });

    return {
      name: chatName,
      message: '聊天室创建成功',
    };
  }

  async list(userId: number) {
    const chatroomIds = await this.prismaService.userChatroom.findMany({
      where: {
        userId,
      },
      select: {
        chatroomId: true,
      },
    });

    const chatrooms = await this.prismaService.chatroom.findMany({
      where: {
        id: {
          in: chatroomIds.map((item) => item.chatroomId),
        },
      },
      select: {
        id: true,
        name: true,
        type: true,
        createTime: true,
      },
    });

    const res = [];
    for (let i = 0; i < chatrooms.length; i++) {
      const userIds = await this.prismaService.userChatroom.findMany({
        where: {
          chatroomId: chatrooms[i].id,
        },
        select: {
          userId: true,
        },
      });
      res.push({
        ...chatrooms[i],
        userCount: userIds.length,
        userIds: userIds.map((item) => item.userId),
      });
    }

    return res;
  }

  async members(chatroomId: number) {
    const userIds = await this.prismaService.userChatroom.findMany({
      where: {
        chatroomId,
      },
      select: {
        userId: true,
      },
    });

    return await this.prismaService.user.findMany({
      where: {
        id: {
          in: userIds.map((item) => item.userId),
        },
      },
    });
  }

  async info(chatroomId) {
    const chatroom = await this.prismaService.chatroom.findUnique({
      where: {
        id: chatroomId,
      },
    });

    return {
      ...chatroom,
      users: await this.members(chatroomId),
    };
  }

  async join(chatroomId: number, joinUserId: number) {
    const chatroom = await this.prismaService.chatroom.findUnique({
      where: {
        id: chatroomId,
      },
    });

    if (!chatroom.type) {
      return {
        message: '不是群聊，无法加入',
      };
    }

    const members = await this.members(chatroomId);

    if (members.find((item) => item.id === joinUserId)) {
      return {
        message: '已经在聊天室中',
      };
    }

    await this.prismaService.userChatroom.create({
      data: {
        userId: joinUserId,
        chatroomId,
      },
    });

    return {
      message: '加入聊天室成功',
    };
  }

  async quit(chatroomId: number, quitUserId: number) {
    const chatroom = await this.prismaService.chatroom.findUnique({
      where: {
        id: chatroomId,
      },
    });

    if (!chatroom.type) {
      return {
        message: '不是群聊，无法退出',
      };
    }

    const members = await this.members(chatroomId);

    if (!members.find((item) => item.id === quitUserId)) {
      return {
        message: '不在聊天室中',
      };
    }

    await this.prismaService.userChatroom.deleteMany({
      where: {
        userId: quitUserId,
        chatroomId,
      },
    });

    return {
      message: '退出聊天室成功',
    };
  }
}
